import xbmc
import xbmcgui
import os
import xmlrpclib
from pickle import Pickler, Unpickler
from os import path

server_proxy = "http://localhost:9191" 
setting_file = path.join(os.getcwd(), "voip-settings.qlive")

class SettingWindow(xbmcgui.WindowDialog) :
	def __init__(self):
		self.initVariable()
		self.initComponent()

	def initVariable(self):
		self.settings = {"SERVER":"", "PORT" :"", "USERNAME":"", "PASSWORD":""}

		try :
			self.settings = self.loadSetting()
			print self.settings
		except :
			self.settings = {"SERVER":"", "PORT" :"", "USERNAME":"", "PASSWORD":""}

	def loadSetting(self):
		global setting_file

		f = open(setting_file,"rb")
		unp = Unpickler(f)
		settings = unp.load()
		f.close()
		return settings

	def saveSetting(self):
		self.settings["SERVER"] = self.server_item.getLabel2()
		self.settings["PORT"] = self.port_item.getLabel2()
		self.settings["USERNAME"] = self.user_item.getLabel2()
		#self.settings["PASSWORD"] = self.pass_item.getLabel2()
		

		global setting_file
		f = open(setting_file, "wb")
		p = Pickler(f)
		p.dump(self.settings)
		f.close()
	
	def initComponent(self):
		self.setCoordinateResolution(1)
		self.createImage(0,0,self.getWidth(), self.getHeight(),"background.gif")
		
		'''
		self.sip_server_label = self.createLabel(100,100,200,30, "SIP server ")
		self.sip_user_label = self.createLabel(100,130,200,30, "SIP user ")
		self.sip_pass_label = self.createLabel(100,160,200,30, "SIP password")
		'''

		self.createLabel(30,30,200,20, "General Settings")
		self.setting_list = self.createSettingList(30,60)

		self.createLabel(30,200,200,20, "Audio Codecs")
		self.codec_list = self.createCodecList(30,230)

	
		self.setting_list.controlLeft(self.codec_list)
		self.codec_list.controlRight(self.setting_list)

		self.setFocus(self.setting_list)
		
	def createSettingList(self,x,y):
		setting_list = xbmcgui.ControlList(x,y,self.getWidth()-60, 200,  buttonFocusTexture =  os.path.join( os.getcwd(), 'h2.png'))

		self.server_item = self.createListItem("SIP server", self.settings["SERVER"])
		self.port_item = self.createListItem("SIP server port", self.settings["PORT"])
		self.user_item = self.createListItem("SIP user", self.settings["USERNAME"])
		self.pass_item = self.createListItem("SIP password", self.settings["PASSWORD"])

		self.addControl(setting_list)

		setting_list.addItem(self.server_item)
		setting_list.addItem(self.port_item)
		setting_list.addItem(self.user_item)
		setting_list.addItem(self.pass_item)

		return setting_list

	def createCodecList(self,x,y):
		global server_proxy
		proxy = xmlrpclib.ServerProxy(server_proxy)
		datas = proxy.getCodecList()
		keys = datas.keys()
		keys.sort()

		codec_list = xbmcgui.ControlList(x,y,self.getWidth()-60,250,  buttonFocusTexture =  os.path.join( os.getcwd(), 'h2.png'))
		self.addControl(codec_list)

		for key in keys :
			data = datas[key]
			name = data["NAME"]
			bandwidth = data["FREQUENCY"]
			
			label = "%-10s%10d kHz" % (name, int(bandwidth) / 1000)
			item = xbmcgui.ListItem()
			item.setLabel(label)
			item.setLabel2("Enable")

			codec_list.addItem(item)

		return codec_list

	def createListItem(self,label1, label2):
		list_item = xbmcgui.ListItem(label1, label2, 'blank-poster.tbn', 'poster.tbn')
		return list_item	

	def createImage(self,x,y,w,h,file):
		abs_file = path.join(os.getcwd() , file)
		image = xbmcgui.ControlImage(x,y,w,h, abs_file)	
		self.addControl(image)
	
	def createLabel(self, x, y, w, h, text):
		labelx = xbmcgui.ControlLabel(x,y,w,h ,text)
		self.addControl(labelx)
		return labelx

	def createTextBox(self,x,y,w,h):
		text_box = xbmcgui.ControlTextBox(x,y,w,h)
		self.addControl(text_box)
		return text_box

	def onControl(self, control):
		if control == self.setting_list :
			selected_item = self.setting_list.getSelectedItem()
			if selected_item == self.server_item :
				server = self.getInput(selected_item.getLabel2(), "Enter SIP server", False)
				selected_item.setLabel2(server)
			elif selected_item == self.user_item :
				user = self.getInput(selected_item.getLabel2(), "Enter SIP user", False)
				selected_item.setLabel2(user)
			elif selected_item == self.pass_item :
				passwd = self.getInput(selected_item.getLabel2(), "Enter SIP password", True)
				selected_item.setLabel2("*****")
				self.settings["PASSWORD"] = passwd
			elif selected_item == self.port_item :
				port = self.getInput(selected_item.getLabel2(), "Enter SIP port", False)
				selected_item.setLabel2(port)
		elif control == self.codec_list :
			selected_item = self.codec_list.getSelectedItem()
			label2 = selected_item.getLabel2()
			if label2 == "Disable" :
				selected_item.setLabel2("Enable")
			elif label2 == "Enable" :
				selected_item.setLabel2("Disable")

		self.saveSetting()

	def getInput(self, default, title, hidden):
		kb = xbmc.Keyboard('', title, hidden)
		kb.doModal()
		if (kb.isConfirmed()):
			return kb.getText()
		else :
			return default

	def onAction(self, action):
		if action == 10 : # esc
			self.saveSetting()
			try :
				self.updateAccount()
			except Exception, ex:
				print "update account error ..", ex
			self.close()

	def updateAccount(self):
		proxy = xmlrpclib.ServerProxy("http://localhost:9877")
		proxy.updateAccount(self.settings)

s = SettingWindow()
s.doModal()
	
